<template>
  <div>
    <el-dialog
      :title="info.title + '商品'"
      :visible.sync="info.isShow"
      width="50%"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="一级分类" prop="first_cateid">
          <el-select v-model="ruleForm.first_cateid" @change="firstChange">
            <el-option label="请选择" :value="0"></el-option>
            <el-option
              v-for="(item, index) in firstList"
              :key="index"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类" prop="second_cateid">
          <el-select v-model="ruleForm.second_cateid">
            <el-option label="请选择" :value="0"></el-option>
            <el-option
              v-for="(item, index) in secondList"
              :key="index"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsname">
          <el-input v-model="ruleForm.goodsname"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input v-model="ruleForm.price"></el-input>
        </el-form-item>
        <el-form-item label="市场价格" prop="market_price">
          <el-input v-model="ruleForm.market_price"></el-input>
        </el-form-item>
        <el-form-item label="商品图片">
          <!-- action：上传的地址 -->
          <!-- list-type：设置文件列表的样式 -->
          <!-- on-preview：点击预览时的函数 -->
          <!-- on-remove：点击删除时的函数 -->
          <!-- auto-upload:自动上传 -->
          <!-- file-list:上传的历史文件列表 -->
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleChange"
            :file-list="fileList"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品规格" prop="sepcsid">
          <el-select v-model="ruleForm.sepcsid" @change="sepcsChange">
            <el-option label="请选择" :value="0"></el-option>
            <el-option
              v-for="(item, index) in sepcsList"
              :key="index"
              :label="item.specsname"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规格属性值">
          <el-select v-model="ruleForm.sepcsattr" multiple>
            <el-option label="请选择" :value="0"></el-option>
            <el-option
              v-for="(item, index) in attrList"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否新品">
          <el-radio-group v-model="ruleForm.isnew">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否热卖">
          <el-radio-group v-model="ruleForm.ishot">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="ruleForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button
            class="btn"
            v-if="info.title === '添加'"
            type="primary"
            @click="submitForm('ruleForm')"
            >立即添加</el-button
          >
          <el-button
            class="btn"
            v-if="info.title === '修改'"
            type="primary"
            @click="submitForm('ruleForm')"
            >立即修改</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { getCateTreeListFn, addUserFn, editUserFn, getCateListByPidFn, getSpecsListFn, getSpecsInfoByIdFn } from "../../apis";
export default {
  props: ["info"],
  data() {
    return {
      // 上传过的历史文件的列表，element ui已经指定了结构
      fileList: [{ name: "", url: "" }],
      ruleForm: {
        first_cateid: 0,
        second_cateid: 0,
        goodsname: "",
        img: "",
        description: "",
        price: 0,
        market_price: 0,
        sepcsid: 0,
        sepcsattr: "",
        isnew: 1,
        ishot: 1,
        status: 1,
      },
      rules: {
        first_cateid: [
          { required: true, message: "请选择一级分类", trigger: "blur" },
        ],
        second_cateid: [
          { required: true, message: "请选择二级分类", trigger: "blur" },
        ],
        sepcsid: [
          { required: true, message: "请选择商品规格", trigger: "blur" },
        ],
        sepcsattr: [
          { required: true, message: "请选择规格属性值", trigger: "blur" },
        ],
        goodsname: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
        market_price: [
          { required: true, message: "请输入市场价格", trigger: "blur" },
        ],
      },
      // 一级分类下拉框的数组
      firstList: [],
      // 二级分类下拉框的数组
      secondList: [],
      // 规格下拉框的数组
      sepcsList: [],
      // 规格属性值下拉框的数组
      attrList: []
    };
  },
  created() {
    // 发请求，获取菜单
    this.getRoleList();
    // 发请求，获取规格
    this.getSpecsList();
  },
  methods: {
    setValue(data) {
      // 每次打开弹窗，先清空文件列表
      this.fileList = [];
      if (data.img) {
        // img不为空说明有图片，需要展示
        this.fileList.push({
          url: this.$host + data.img,
          name: "u-shop",
        });
      }
      // 设置弹窗中表单的值
      // 深拷贝，避免数据影响
      this.ruleForm = { ...data };
    },
    async getRoleList() {
      let res = await getCateTreeListFn();
      // 给下拉框的数组赋值
      this.firstList = res.list;
    },
    submitForm(formName) {
      // this.$refs[formName]获取表单的dom节点
      // validate 校验函数，element 自带的函数
      this.$refs[formName].validate((valid) => {
        // valid 校验的结果
        if (valid) {
          this.add();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 真的添加了
    async add() {
      let res;
      if (this.info.title === "添加") {
        res = await addUserFn(this.ruleForm);
      } else {
        res = await editUserFn(this.ruleForm);
      }
      if (res.code === 200) {
        this.closed();
        // 通知list组件更新数据
        this.$emit("update");
        // 提示成功
        this.$message({
          type: "success",
          message: res.msg,
        });
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 关闭弹窗
    closed() {
      this.info.isShow = false;
    },
    // 修改文件时触发的函数
    handleChange(file, fileList) {
      this.ruleForm.img = fileList[0].raw;
    },
    async firstChange() {
      // 当一级分类变化时，二级分类会随之变化
      let res = await getCateListByPidFn({pid: this.ruleForm.first_cateid})
      this.secondList = res.list;
    },
    async sepcsChange() {
      // 当规格变化时，规格属性值会随之变化
      let res = await getSpecsInfoByIdFn({id: this.ruleForm.sepcsid})
      console.log(res);
      this.attrList = res.list[0].attrs;
    },
    // 获取商品规格列表
    async getSpecsList() {
      let res = await getSpecsListFn({size: 100, page: 1});
      this.sepcsList = res.list;
    },
  },
};
</script>

<style>
</style>